<template>
  <a-layout>
    <a-layout-content style="padding: 24px;">
      <a-card v-if="article" class="article-detail">
        <!-- Title -->
        <h1 class="article-title">{{ article.title }}</h1>

        <!-- Content -->
        <p class="article-content">{{ article.content }}</p>

        <!-- Action Buttons -->
        <a-row :gutter="16" class="article-actions">
          <a-col :span="6">
            <a-button block type="primary" @click="likeArticle">
              <template #icon><LikeOutlined /></template> Like
            </a-button>
          </a-col>
          <a-col :span="6">
            <a-button v-if="!authStore.isGuest && !authStore.isUser" block danger @click="deleteArticle">
              <template #icon><DeleteOutlined /></template> Delete
            </a-button>
          </a-col>
          <a-col :span="6">
            <a-button v-if="!authStore.isGuest && !authStore.isUser" block type="dashed" @click="editArticle">
              <template #icon><EditOutlined /></template> Modify
            </a-button>
          </a-col>
          <a-col :span="6">
            <a-button block @click="goBack">
              <template #icon><ArrowLeftOutlined /></template> Back
            </a-button>
          </a-col>
        </a-row>

        <!-- Like Count -->
        <div class="like-count">
          <a-tag color="blue">
            <template #icon><LikeOutlined /></template> Likes: {{ like }}
          </a-tag>
        </div>
      </a-card>
      <!-- Edit Announcement Modal -->
      <a-modal v-model:visible="dialogVisible" title="Edit Announcement" width="30%">
        <a-form :model="editForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-form-item label="Title">
            <a-input v-model:value="editForm.title"></a-input>
          </a-form-item>
          <a-form-item label="Content">
            <a-textarea v-model:value="editForm.content" :rows="4"></a-textarea>
          </a-form-item>
        </a-form>
        <template #footer>
          <a-button @click="dialogVisible = false">Cancel</a-button>
          <a-button type="primary" @click="submitEdit">Confirm</a-button>
        </template>
      </a-modal>
    </a-layout-content>
  </a-layout>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import axios from "../axios";
import type { Article, Like } from "../types/Article";
import { message } from "ant-design-vue";
import { useAuthStore } from '../store/auth';

const article = ref<Article | null>(null);
const route = useRoute();
const router = useRouter();
const like = ref<number>(0);
const authStore = useAuthStore();
const dialogVisible = ref<boolean>(false);
const editForm = ref({
  title: '',
  content: '',
  preview: ""
});

const { id } = route.params;

const fetchArticle = async () => {
  try {
    const response = await axios.get<Article>(`/articles/${id}`);
    article.value = response.data.data;
  } catch (error) {
    const axiosError = error as { response: { data: { message: string; code: number } } };
    if (axiosError.response?.data?.code === 500) {
      message.error(axiosError.response.data.message || 'Article error, please try again.');
    }else if (axiosError.response?.data?.code === 404) {
      message.error(axiosError.response.data.message || 'Article not found');
    } else {
      message.error('Failed to fetch article, please try again.');
    }
  }
};

const likeArticle = async () => {
  try {
    const res = await axios.post<Like>(`/articles/${id}/like`);
<<<<<<< HEAD
    // 不再使用 res.data.data.like，直接刷新数据
    await fetchLike(); // 重新获取点赞数
    message.success('点赞成功');
=======
    like.value = res.data.data.like;
    await fetchLike();
>>>>>>> parent of 87155d1 (refactor(log): 优化日志记录和处理)
  } catch (error) {
    const axiosError = error as { response: { data: { message: string; code: number } } };
    if (axiosError.response?.data?.code === 500) {
      message.error(axiosError.response.data.message || 'Failed to like');
    }else if (axiosError.response?.data?.code === 404) {
      message.error(axiosError.response.data.message || 'Article not found');
    } else {
      message.error('Failed to like, please try again.');
    }
  }
};

const fetchLike = async () => {
  try {
    const res = await axios.get<Like>(`/articles/${id}/like`);
    like.value = res.data.data.like;
  } catch (error) {
    const axiosError = error as { response: { data: { message: string; code: number } } };
    if (axiosError.response?.data?.code === 500) {
      message.error(axiosError.response.data.message || 'Failed to fetch like count');
    }else if (axiosError.response?.data?.code === 404) {
      message.error(axiosError.response.data.message || 'Article not found');
    } else {
      message.error('Failed to fetch like count, please try again.');
    }
  }
};

const deleteArticle = async () => {
  try {
    await axios.delete(`/articles/${id}`);
    article.value = null;
    like.value = 0;
    message.success('Deleted successfully');
    router.push({ name: 'News' });
  } catch (error) {
    const axiosError = error as { response: { data: { message: string; code: number } } };
    if (axiosError.response?.data?.code === 500) {
      message.error(axiosError.response.data.message || 'Failed to delete article');
    } else {
      message.error('Failed to delete article, please try again.');
    }
  }
};

const editArticle = () => {
  if (article.value) {
    editForm.value = {
      title: article.value.title,
      content: article.value.content,
      preview: article.value.preview
    };
    dialogVisible.value = true;
  }
};

const submitEdit = async () => {
  try {
    if (editForm.value.content) {
      editForm.value.preview = editForm.value.content.substring(0, 100);
    }
    await axios.put(`/articles/${id}`, editForm.value);
    await fetchArticle();
    dialogVisible.value = false;
    message.success('Updated successfully');
    router.push({ name: 'News' });
  } catch (error) {
    const axiosError = error as { response: { data: { message: string; code: number } } };
    if (axiosError.response?.data?.code === 500) {
      message.error(axiosError.response.data.message || 'Failed to update article');
    } else {
      message.error('Failed to update article, please try again.');
    }
  }
};

const goBack = () => {
  router.go(-1);
};

onMounted(fetchArticle);
onMounted(fetchLike);
</script>

<style scoped>
.article-detail {
  margin: 20px auto;
  padding: 24px;
  max-width: 800px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: #fff;
}

.article-title {
  font-size: 2.2em;
  margin-bottom: 24px;
  color: #333;
  text-align: center;
}

.article-content {
  font-size: 1.1em;
  line-height: 1.8;
  color: #555;
  margin-bottom: 24px;
}

.article-actions {
  margin-top: 24px;
}

.like-count {
  margin-top: 16px;
  text-align: right;
}

.no-data {
  text-align: center;
  font-size: 1.2em;
  color: #999;
  margin-top: 40px;
}

.ant-btn {
  transition: all 0.3s ease;
}

.ant-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.ant-modal-body {
  padding: 24px;
}

.ant-form-item {
  margin-bottom: 16px;
}

.ant-input, .ant-textarea {
  border-radius: 4px;
}

.ant-tag {
  font-size: 1em;
  padding: 4px 8px;
}
</style>